package com.ws.server.NettyServer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * 使用netty实现websocket
 */
public class NettyServer {
    private Integer port;

    public NettyServer(Integer port) {
        this.port = port;
    }

    /**
     * 启动NettyServer
     */
    public void start() {
        //创建主线程，用于接收连接请求
        NioEventLoopGroup bossLoopGroup = new NioEventLoopGroup();
        //创建工作现场，用于处理从主线程分配下来的IO
        NioEventLoopGroup workLoopGroup = new NioEventLoopGroup();

        //启动server
        ChannelFuture channelFuture = null;
        try {
            //创建netty服务器
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossLoopGroup, workLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    //子处理器，用于处理workerGroup中的操作;
                    .childHandler(new NettyServerInitializer());
            //启动server
            channelFuture = serverBootstrap.bind(port).sync();
            //监听关闭channel
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //关闭主线程
            bossLoopGroup.shutdownGracefully();
            //关闭从线程
            workLoopGroup.shutdownGracefully();
        }


    }
}
